/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzilla.desk;

import com.yy.bugzilla.desk.tool.BasePane;
import com.yy.bugzillahelp.action.BugAction;
import com.yy.bugzillahelp.action.download.BugCrawlAction;
import com.yy.bugzillahelp.action.server.ServerAction;
import com.yy.bugzillahelp.action.server.ServerConfigAction;
import com.yy.bugzillahelp.data.BugDetailData;
import com.yy.bugzillahelp.data.BugStatus;
import com.yy.bugzillahelp.data.server.ServerConfigData;
import com.yy.bugzillahelp.data.server.ServerData;
import com.yy.bugzillahelp.db.BugzillaHelpDB;
import com.yy.bugzillahelp.tool.SQLTool;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;

/**
 *
 * @author Alan
 */
public class ServerListPane extends BasePane {

    private static final Logger logger = Logger.getLogger(ServerListPane.class.getName());
    private ArrayList<ServerData> connectDatas = new ArrayList<>();
    private ContextMenu contextMenu;
    private TreeView treeView;
    private MainApp mainApp;

    public ServerListPane(MainApp mainApp) {
        this.mainApp = mainApp;
    }

    @Override
    protected Pane generatePane() {
        initDatas();

        treeView = new TreeView();
//        treeView.setStyle("-fx-border-width: 0px;");
        TreeItem<ServerNode> root = new TreeItem<>(new ServerNode("服务器列表"));
        root.setExpanded(true);
        for (ServerData serverData : connectDatas) {
            TreeItem<ServerNode> treeItem = new TreeItem<>(new ServerNode(serverData));
            root.getChildren().add(treeItem);
        }
        treeView.setRoot(root);

        generateContextMenu();
        treeView.setContextMenu(contextMenu);
//        treeView.setOnMouseClicked(new EventHandler<MouseEvent>() {
//
//            @Override
//            public void handle(MouseEvent t) {
//                if (t.getButton() == MouseButton.SECONDARY) {
//                    TreeItem<ServerNode> item = (TreeItem<ServerNode>) treeView.getSelectionModel().getSelectedItem();
//                    if (item == null) {
//                        return;
//                    }
//
//                    ServerData serverData = item.getValue().getServerData();
//                    if (serverData != null) {
//                        System.out.println(t.getX() + "," + t.getY());
//                        contextMenu.show(treeView, t.getScreenX(), t.getScreenY());
//                    }
//                }
//            }
//        });

        BorderPane borderPane = new BorderPane();
//        borderPane.setStyle("-fx-border-width: 0px;");
        borderPane.setCenter(treeView);
        return borderPane;
    }

    private void initDatas() {
        Connection con = BugzillaHelpDB.getConnection();
        ArrayList<ServerData> list = ServerAction.searchAll(con);
        connectDatas.addAll(list);
        SQLTool.closeConnection(con);
    }

    private ServerData getSelectedServerData() {
        TreeItem<ServerNode> item = (TreeItem<ServerNode>) treeView.getSelectionModel().getSelectedItem();
        if (item == null) {
            return null;
        }

        return item.getValue().getServerData();
    }

    private void generateContextMenu() {
        contextMenu = new ContextMenu() {

            @Override
            protected void show() {
                ServerData serverData = getSelectedServerData();
                if (serverData != null) {
                    super.show();
                }
            }
        };

        contextMenu.getItems().add(createMenuItem("编辑"));
        contextMenu.getItems().add(createMenuItem("删除"));
        contextMenu.getItems().add(new SeparatorMenuItem());
        Menu search = new Menu("查询");
        search.getItems().add(createMenuItem("未解决的"));
        contextMenu.getItems().add(search);
        contextMenu.getItems().add(createMenuItem("列表"));
        contextMenu.getItems().add(new SeparatorMenuItem());
        contextMenu.getItems().add(createMenuItem("更新"));
    }

    private MenuItem createMenuItem(final String text) {
        MenuItem mi = new MenuItem(text);
        mi.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                if ("列表".equals(text)) {
                    doList("", null);
                } else if ("更新".equals(text)) {
                    doReload();
                } else if ("未解决的".equals(text)) {
                    doList("-未解决的", BugStatus.getOpenStatus());
                }
            }
        });
        return mi;
    }

    private void doList(String titleSufix, BugStatus[] statuses) {
        ServerData serverData = getSelectedServerData();
        if (serverData == null) {
        } else {
            String tabName = serverData.getConnectName() + titleSufix + BugListPane.BUG_LIST;
            if (!mainApp.getMainTabPane().containsTab(tabName)) {
                BugListPane bugListPane = new BugListPane(mainApp, serverData);
                bugListPane.setBugStatus(statuses);
                mainApp.getMainTabPane().addBugListPane(tabName, bugListPane);
            } else {
                mainApp.getMainTabPane().selectTab(tabName);
            }
        }
    }

    private void doReload() {
        final ServerData serverData = getSelectedServerData();
        if (serverData == null) {
            return;
        }

        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                Connection con = BugzillaHelpDB.getConnection();
                logger.log(Level.INFO, "get last flush time...start...");
                ServerConfigData configData = ServerConfigAction.searchByServerId(con, serverData.getId());
                logger.log(Level.INFO, configData.toString());
                logger.log(Level.INFO, "get last flush time...end...");
                long lastFlushTime = configData.getLastFlushTime();
                String ids;//= "1632,1637,1640,895,1017,1535,1648,954,896,1058,1128,1453,1469,1493,1531,1533,1572,1580,934,936,939,1507,886,887,1090,1133,1271,1312,1320,1378,1428,1498,1512,1519,1522,1526,1528,1560,904,938,989,926,1249,874,875,890,1445,872,1438,1465,1482,1508,1513,1514,1546,1598,1599,1600,1602,1607,1611,1612,1617,1621,1626,1634,1635,1644,1517,979,1566,1643,1473,869,1574,1603,1552,1575,1608,1650,1583,1629,976,978,1511,1394,1477,1577,929,1381,1641,911,935,999,1169,1538,1539,975,1008,1010,1308,1463,1464,777,780,782,971,945,958,964,1435,711,916,1238,1452,1614,1616,1433,1594,1631,1478,1234,1568,1172,1525,1639,1364,1443,1050,1137,1461,1604,1094,1524,1627,968,210,281,286,299,306,312,409,1521,1584,1595,144,455,501,507,508,170,301,356,208,504,509,161,222,305,313,329,335,338,355,468,497,498,165,175,186,205,216,217,219,247,248,249,253,332,343,345,347,352,353,374,375,402,435,447,459,578,160,193,250,251,279,300,302,303,314,323,328,354,454,499,510,1630,1636,177,180,185,189,228,244,252,254,267,280,283,288,292,293,295,296,330,392,393,460,461,1624,1628,1651,232,365,456,503,1613,1620,110,234,290,191,196,199,209,213,235,238,287,291,307,476,50,145,183,282,585,586,179,194,230,358,360,370,372,377,382,383,384,395,453,583,162,169,173,174,178,187,195,198,200,201,202,203,204,214,215,221,226,240,259,265,266,285,363,366,368,373,379,386,397,430,451,192,231,241,242,255,389,390,391,471,511,588,112,114,163,166,190,211,233,239,245,268,269,294,309,496,1250,181,188,870,1592,1609,1642,1645,1649,182,458,467,746,167,220,396,398,25,479,841,526,388,478,184,212,258,260,394,818,487,967,658,1520,227,387,940,1011,898,965,52,197,275,308,317,318,321,324,326,361,369,444,465,466,470,491,492,274,334,357,417,469,483,486,28,263,278,148,207,273,289,298,304,311,362,364,378,385,413,438,442,443,472,556,559,562,27,327,333,339,350,351,419,422,439,481,488,500,521,524,525,528,540,555,564,566,569,573,574,575,584,4,223,224,246,315,316,420,463,485,505,519,520,523,530,532,536,550,558,563,568,571,572,590,42,44,47,51,54,57,58,62,63,64,65,68,74,77,82,84,86,87,88,89,90,91,117,140,168,218,225,272,276,277,284,297,337,341,342,344,346,359,367,371,376,380,381,400,401,403,410,414,416,418,423,424,425,426,427,428,429,431,432,433,434,436,437,440,441,445,448,450,452,464,473,474,475,480,484,490,494,502,506,512,513,515,516,535,543,544,546,547,548,549,551,560,561,577,579,580,581,582,587,589,593,594,596,598,599,600,868,877,1045,236,237,243,262,411,412,446,557,597,141,270,310,319,320,325,331,336,340,348,349,399,404,405,406,407,408,415,421,449,457,462,477,482,489,518,529,531,537,538,539,542,552,554,565,567,570,576,229,1480,1486,1309,1490,1436,1479,1505,1515,1385,991,972,1403,1368,125,142,154,158,264,614,620,622,657,683,684,696,697,838,922,928,949,951,985,986,987,988,994,995,996,1001,1007,1013,1015,1021,1024,1026,1027,1028,1029,1032,1033,1034,1037,1039,1042,1044,1051,1063,1074,1075,1079,1080,1081,1084,1123,1153,1156,1157,1160,1164,1171,1173,1176,1178,1180,1184,1188,1199,1214,1215,1231,1244,1264,1275,1288,1289,1293,1301,1303,1315,1371,1444,1448,1449,1467,1483,1501,1518,1529,1542,1554,1567,1569,1578,1579,1582,606,607,702,835,836,844,876,1246,1267,1290,1291,1305,1307,1317,1354,1358,1387,1419,1437,1442,1471,1489,1555,1589,1251,729,756,790,105,131,171,206,834,1002,616,648,700,156,609,615,715,832,955,1218,1232,1240,1261,1269,1279,1294,1319,1466,106,108,113,120,123,126,127,128,147,151,152,159,612,619,621,628,654,655,656,724,727,833,837,839,873,1087,1243,1314,1413,1500,18,146,164,602,603,608,610,613,623,624,629,686,701,719,807,948,953,990,1005,1006,1031,1041,1056,1276,1367,1537,912,1217,1233,1280,1025,1216,1359,1414,1523,653,699,707,843,963,1167,1192,1203,1204,1211,1220,1221,1222,1223,1245,1285,1310,1345,1424,1472,1485,1487,1497,1556,1638,19,29,122,133,134,176,617,618,630,631,632,639,640,652,666,708,722,730,748,754,758,767,792,825,826,883,893,899,901,907,908,910,917,923,927,932,933,942,943,950,952,962,966,970,973,993,997,1003,1014,1016,1018,1019,1030,1035,1036,1038,1040,1046,1047,1052,1053,1055,1057,1065,1067,1069,1071,1073,1076,1077,1078,1083,1085,1096,1105,1107,1110,1114,1115,1118,1119,1131,1135,1151,1152,1181,1195,1202,1213,1230,1237,1241,1252,1331,1332,1334,1356,1373,1400,1430,1432,1439,1454,1460,1470,1474,1475,1476,1481,1495,1503,1509,1516,1527,1550,1571,1573,1601,1610,625,636,704,735,774,786,791,795,813,830,846,855,859,1054,1068,1104,1126,1224,1225,1239,1273,1292,1306,1321,1322,1325,1326,1330,1360,1369,1370,1380,1382,1386,1405,1406,1407,1410,1411,1416,1421,1429,1450,1451,1494,1502,1504,1543,1593,1597,1605,1622,1623,1272,861,862,863,866,785,763,789,104,155,322,638,747,751,759,760,773,778,779,784,794,800,802,848,706,755,762,850,852,853,913,1219,1226,1228,1300,1313,1324,1338,1362,1397,1420,1427,1606,17,30,31,37,39,41,107,115,129,132,135,136,137,143,153,627,805,809,824,831,847,854,857,880,884,918,983,992,1248,1256,1284,1355,1384,1389,1390,1393,1418,1425,1426,1547,40,604,605,637,673,693,705,710,781,783,808,810,811,823,851,864,919,925,944,956,959,969,977,1022,1023,1066,1117,1129,1149,1175,1177,1189,1193,1196,1282,1329,1395,1398,1549,787,801,849,856,860,1198,1206,1376,1377,1379,1408,1447,1468,1190,1208,1323,1341,1346,1399,633,634,635,757,761,764,765,768,771,796,798,799,821,827,894,1043,1124,1182,1242,1247,1255,1257,1304,1318,1333,1402,1409,1434,1459,20,22,34,36,688,766,769,770,815,817,822,882,885,891,897,903,905,915,921,946,957,980,1020,1049,1060,1072,1089,1108,1113,1116,1140,1142,1150,1155,1186,1229,1265,1277,1278,1283,1302,1340,1343,1344,1350,1357,1363,1374,1375,1383,1396,1415,1440,1441,1446,1456,1458,1462,1491,1499,1510,1530,1532,1534,1536,1540,1544,1545,1548,1551,1553,1558,1563,1564,1565,1570,1576,1581,1591,1615,1618,709,772,797,840,1161,1185,1205,1274,1328,1335,1353,1365,1366,1388,1392,1412,1422,1484,1557,1559,1561,1562,1585,1586,1587,1588,1590,1596,1619,1625,749,814,828,842,725,803,806,829,865,867,914,1099,1139,1311,1342,1423,1457,23,24,72,728,742,812,816,982,1064,1095,1127,1260,1263,1646,646,752,788,819,858,871,888,909,920,924,941,1170,1212,1270,1348,1372,776,804,1147,1163,1191,1197,1201,1316,1132,1194,1207,1299,1336,1337,1351,1417,775,820,1259,1287,1339,1347,1401,1404,626,745,881,947,961,984,1158,1227,1262,1286,1431,1492,1496,1253,732,733,734,738,739,611,1000,643,937,960,981,1281,35,698,703,879,694,1082,974,1166,1296,889,878,892,3,15,32,33,45,59,61,78,79,81,94,95,119,139,256,257,261,271,493,495,514,517,522,527,533,534,541,545,553,591,592,595,647,660,671,692,793,902,930,998,1009,1012,1070,1088,1091,1092,1093,1098,1101,1103,1106,1109,1111,1112,1120,1121,1122,1125,1130,1134,1138,1141,1143,1144,1145,1146,1148,1154,1159,1162,1165,1168,1179,1187,1210,1235,1254,1266,1268,1455,1488,1506,1541,1647,678,679,680,681,682,689,713,1061,1209,6,7,8,9,12,13,14,695,716,736,737,740,601,670,1174,10,109,138,662,663,718,721,741,744,101,726,750,753,900,906,1004,1327,1352,1361,1633,2,5,11,16,21,26,38,43,46,48,49,53,55,56,60,66,67,69,70,71,75,76,80,83,85,92,93,96,97,98,99,100,102,103,121,124,130,149,150,157,172,641,642,650,661,667,668,717,720,723,731,743,931,1059,1258,1298,1391,644,645,649,651,664,669,672,674,676,677,685,687,691,714,845,1097,1136,1183,1200,1086,1100,1236,1062,1295,1297,1349,659,665,675,690,712,1048,1102";

                logger.log(Level.INFO, "get changed ids...start...");
                long currentTimeMillis = System.currentTimeMillis();
                if (lastFlushTime < 100) {
                    ids = BugCrawlAction.getAllIds(serverData);
                } else {
                    String timeInterval;
                    long interval = currentTimeMillis - lastFlushTime;
                    long hours = interval / 1000 / 60 / 60;
                    if (hours > 24) {
                        timeInterval = (hours / 24 + 1) + "d";
                    } else {
                        timeInterval = (hours + 1) + "h";
                    }
                    ids = BugCrawlAction.getIdsByTime(serverData, timeInterval);
                }
                System.out.println("get changed ids...end...");

                String[] idArray = ids.split(",");
                int pos = 0;
                while (pos < idArray.length) {
                    String ids1 = getIds(idArray, pos, 100);

                    logger.log(Level.INFO, "ids: {0}", ids1);
                    String xmlById = BugCrawlAction.getXMLByIdWithoutAttachment(serverData, ids1);

                    logger.log(Level.INFO, "xml: {0}", xmlById);

                    logger.log(Level.INFO, "parse xml...");
                    ArrayList<BugDetailData> detailDatas = BugCrawlAction.parseXML(xmlById);

                    logger.log(Level.INFO, "insert bug details to db");
                    BugAction.updateList(con, detailDatas, serverData.getId());

                    pos += 100;
                }

                ServerConfigAction.updateLastFlushTime(con, serverData.getId(), currentTimeMillis);
                SQLTool.closeConnection(con);

                logger.log(Level.INFO, "Reload complete.");

                flushBugListPane();
            }
        });

        thread.start();
    }

    private void flushBugListPane() {
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                HashMap<String, BugListPane> bugListPaneMap = mainApp.getMainTabPane().getBugListPaneMap();
                for (BugListPane bugListPane : bugListPaneMap.values()) {
                    bugListPane.reflush();
                }
            }
        });
    }

    private String getIds(String[] ids, int startPos, int length) {
        if (ids.length > startPos) {
            StringBuilder sb = new StringBuilder();
            for (int i = startPos, count = 0; i < ids.length && count < length; i++, count++) {
                sb.append(ids[i]).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } else {
            return "";
        }
    }

    class ServerNode {

        private ServerData serverData;
        private String text;

        public ServerNode(String text) {
            this.text = text;
        }

        public ServerNode(ServerData serverData) {
            this.serverData = serverData;
            this.text = serverData.getConnectName();
        }

        public ServerData getServerData() {
            return serverData;
        }

        public String getText() {
            return text;
        }

        @Override
        public String toString() {
            return text;
        }
    }
}
